import serial
from datetime import datetime
import time
import codecs


class jy901sRead():
    def __init__(self, serial):
        self.ser = serial
        self.accData = []

    def read(self):
        checksum = 0
        data = self.ser.read(1)
        if data != b'\x55':
            return []
        checksum += int(codecs.encode(data, 'hex'), 16)
        # print(f"x55：一组数据开始传输: {datetime.fromtimestamp(time.time())}")
        data = self.ser.read(1)
        if data == b'\x51':
            checksum += int(codecs.encode(data, 'hex'), 16)
            # print(f"x51：加速度数据开始传输: {datetime.fromtimestamp(time.time())}")
            return self.readData(0, checksum, 16)
        elif data == b'\x52':
            checksum += int(codecs.encode(data, 'hex'), 16)
            # print(f"x52：角速度数据开始传输: {datetime.fromtimestamp(time.time())}")
            return self.readData(1, checksum, 2000)
        elif data == b'\x53':
            checksum += int(codecs.encode(data, 'hex'), 16)
            # print(f"x51：角度数据开始传输: {datetime.fromtimestamp(time.time())}")
            return self.readData(2, checksum, 180)
        else:
            return []

    def readData(self, type, checksum, ratio):
        hexVal = []
        dataList = []
        dataList.append(type)
        # data
        for i in range(8):
            data = self.ser.read(1)
            # print(f"data:{datetime.fromtimestamp(time.time())}")
            # void
            if data == b'':
                print('error')
                break
            data = int(codecs.encode(data, 'hex'), 16)
            hexVal.append(data)
            checksum = checksum + data

        data = self.ser.read(1)
        if data != b'':
            if checksum % 256 == int(codecs.encode(data, 'hex'), 16):
                dataList.append((hexVal[1] << 8) | (hexVal[0]))
                dataList.append((hexVal[3] << 8) | (hexVal[2]))
                dataList.append((hexVal[5] << 8) | (hexVal[4]))
                for i in range(3):
                    if dataList[i + 1] > 32767:
                        dataList[i + 1] = dataList[i + 1] - 65535
                    dataList[i + 1] = dataList[i + 1] / 32768 * ratio
                if type == 0:
                    self.accData.append(dataList[3])
                    if len(self.accData) > 100:
                        del self.accData[0]
                    # print(self.accData)
        return dataList

    def read_acc(self):
        return self.accData


'''
# 设置串口参数
# ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
# win
ser = serial.Serial('COM6', 9600, timeout=1)


def read_data():
    while True:
        checksum = 0
        # 读取指定长度的原始数据包
        data = ser.read(1)
        # head
        if data == b'\x55':
            print(f"一组数据开始：:{datetime.fromtimestamp(time.time())}")

            # print('start')
            checksum = checksum + int(codecs.encode(data, 'hex'), 16)
            data = ser.read(1)
            # acc
            if data == b'\x51':
                print(f"x51:{datetime.fromtimestamp(time.time())}")
                continue
                print('acc start')
                checksum = checksum + int(codecs.encode(data, 'hex'), 16)
                hexVal = []
                # data
                for i in range(8):
                    data = ser.read(1)
                    print(f"data:{datetime.fromtimestamp(time.time())}")
                    # void
                    if data == b'':
                        print('error')
                        break
                    data = int(codecs.encode(data, 'hex'), 16)
                    hexVal.append(data)
                    checksum = checksum + data
                data = ser.read(1)
                if data != b'':
                    if checksum % 256 == int(codecs.encode(data, 'hex'), 16):
                        print(datetime.fromtimestamp(time.time()))
                        acc = []
                        acc.append((hexVal[1] << 8) | (hexVal[0]))
                        acc.append((hexVal[3] << 8) | (hexVal[2]))
                        acc.append((hexVal[5] << 8) | (hexVal[4]))
                        for i in range(3):
                            if acc[i] > 32767:
                                acc[i] = acc[i] - 65535
                            acc[i] = acc[i] / 32768 * 16
                        print(f'acc:x:{acc[0]} y:{acc[1]} z:{acc[2]}')


if __name__ == "__main__":
    try:
        print("开始读取数据...")
        read_data()
    except KeyboardInterrupt:
        print("停止读取数据")
    finally:
        ser.close()
'''
